<template>
  <div class="setting-container">
    <!-- 卡片区 -->
    <el-card class="box-card">
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName">
        <!-- 角色管理 -->
        <el-tab-pane label="角色管理" name="first">
          <!-- 新增按钮 -->
          <el-row>
            <el-button
              size="small"
              icon="el-icon-plus"
              type="primary"
              @click="addRole"
            >新增角色</el-button>
          </el-row>
          <!-- 表格区 -->
          <el-table style="width: 100%" border :data="rolesList">
            <el-table-column type="index" label="序号" width="120" />
            <el-table-column prop="name" label="角色名" width="240" />
            <el-table-column
              prop="description"
              property="address"
              label="描述"
            />
            <el-table-column property="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="success"
                  @click="setRoles(scope.row.id)"
                >分配权限</el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="editRoles(scope.row.id)"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="delRoles(scope.row.id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页区 -->
          <el-pagination
            :current-page="query.currentPage"
            :page-sizes="[1, 5, 10]"
            :page-size="query.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-tab-pane>

        <!-- 公司信息 -->
        <el-tab-pane label="公司信息" name="second">
          <el-alert
            title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
            type="info"
            show-icon
            :closable="false"
          />
          <el-form label-width="120px" style="margin-top: 50px">
            <el-form-item label="公司名称">
              <el-input
                v-model="Companyinfo.name"
                disabled
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input
                v-model="Companyinfo.companyAddress"
                disabled
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input
                v-model="Companyinfo.mailbox"
                disabled
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="Companyinfo.remarks"
                type="textarea"
                :rows="3"
                disabled
                style="width: 400px"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <!-- 新增/编辑角色的弹框 -->
      <el-dialog :title="isEdit?'编辑角色':'新增角色'" :visible.sync="dialogVisible" width="50%" @close="closeDialogFn">
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addSubmit">立即提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 分配权限的弹框 -->
      <el-dialog
        title="为角色分配权限"
        :visible.sync="assiginPerdialog"
        width="50%"
      >
        <!-- 使用v-if控制子组件的显示，解决数据重叠问题 -->
        <AssignPermission v-if="assiginPerdialog" :role-id="roleId" @closeEvent="assiginPerdialog = false" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getRolesAPI, getCompanyinfoAPI, addRoleAPI, getRoleDetailsAPI, updateRoleAPI, deleteRoleAPI } from '@/api/setting'
import { mapGetters } from 'vuex'
import AssignPermission from './assignPermission.vue'
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      activeName: 'first', // 标签页的当前显示
      query: {
        currentPage: 1, // 当前页码值
        pagesize: 5 // 每页显示多少条
      },
      total: 0, // 数据总条数
      rolesList: [], // 角色列表
      Companyinfo: {},
      dialogVisible: false, // 新增角色弹框显示
      form: {
        // 弹框数据
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      isEdit: false,
      assiginPerdialog: false, // 分配角色的弹框显示
      roleId: ''
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoles()
    this.getCompanyinfo()
  },
  methods: {
    // 获取公司信息的方法
    async getCompanyinfo() {
      const res = await getCompanyinfoAPI(this.companyId)
      // console.log(res)
      this.Companyinfo = res.data
    },

    // 获取所有角色列表
    async getRoles() {
      const res = await getRolesAPI(this.query)
      // console.log(res)
      this.rolesList = res.data.rows
      this.total = res.data.total
    },

    // 点击新增角色，显示弹框，非编辑状态
    addRole() {
      this.dialogVisible = true
      this.isEdit = false
    },

    // 点击编辑角色，显示弹框，编辑状态，数据回填
    async editRoles(id) {
      this.dialogVisible = true
      this.isEdit = true
      // 获取角色详情，进行数据回填
      const res = await getRoleDetailsAPI(id)
      // console.log(res)
      this.form = res.data
    },
    // 点击添加角色提交
    addSubmit() {
      this.$refs.form.validate(async(valid) => {
        // 点击提交，进行兜底验证，根据编辑状态调用不同的接口
        if (valid) {
          if (this.isEdit) {
            const res = await updateRoleAPI(this.form)
            // console.log(res)
            this.$message.success(res.message)
          } else {
            const res = await addRoleAPI(this.form)
            // console.log(res)
            this.$message.success(res.message)
          }
          // 关闭弹框
          this.dialogVisible = false
          // 重新获取角色列表
          this.getRoles()
        }
      })
    },
    // 每页条数发生改变时
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // val为每页显示多少条
      this.query.pagesize = val
      this.getRoles()
    },

    // 当前页面发生改变时
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // val 为当前页码值
      this.query.page = val
      this.getRoles()
    },
    // 分配权限
    setRoles(id) {
      this.assiginPerdialog = true
      this.roleId = id
    },
    // 删除角色
    async delRoles(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message('已取消删除')
      const res = await deleteRoleAPI(id)
      console.log(res)
      // 判断当前页面如果只剩一条数据，则页码值减1
      if (this.rolesList.length === 1) {
        this.query.page--
      }
      // 判断当前页码值小于等于0，则默认显示第一页
      if (this.query.page <= 0) {
        this.query.page = 1
      }
      this.$message.success(res.message)
      this.getRoles()
    },
    // 关闭弹框重置表单
    closeDialogFn() {
      this.form = {
        name: '',
        description: ''
      }
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.setting-container {
  padding: 20px;
}
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
.el-table {
  margin-top: 10px;
}
form.el-form {
  padding: 0 30px 0 20px;
}
.el-form-item__label {
  font-weight: 400;
}
</style>
